//
//  HBAudioTool.m
//  HappyBaby
//
//  Created by lanou on 15/11/28.
//  Copyright © 2015年 华哥. All rights reserved.
//

#import "HBAudioTool.h"

/**
 *  存放所有的音乐播放器
 *  字典: filename作为key, audioPlayer作为value
 */
static NSMutableDictionary *_audioPlayerDict;

@implementation HBAudioTool

/**
 * 初始化
 */
+ (void)initialize
{
    _audioPlayerDict = [NSMutableDictionary dictionary];
}


/**
 *  播放音乐
 *
 *  @param filename 音乐文件名
 */
+ (MPMoviePlayerController *)playMusic:(NSString *)filename
{
    if (!filename) {
        return nil;
    }
    
    // 1.从字典中取出audioPlayer
    MPMoviePlayerController *audioPlayer = _audioPlayerDict[filename];
    
    if (!audioPlayer) {
        // 加载音乐文件
        NSURL *url = [NSURL URLWithString:filename];
        if (!url) {
            return nil;
        }
        
        // 创建audioPlayer
//        audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:url error:nil];
        audioPlayer = [[MPMoviePlayerController alloc]initWithContentURL:url];
        
        //缓冲
        [audioPlayer prepareToPlay];
        
        // 放入字典
        _audioPlayerDict[filename] = audioPlayer;
    }
    
    // 2.播放
    if (audioPlayer.playbackState == MPMoviePlaybackStatePaused) {
        [audioPlayer play];
    }
    return audioPlayer;
}

/**
 *  暂停音乐
 *
 *  @param filename 音乐文件名
 */
+ (void)pauseMusic:(NSString *)filename
{
    if (!filename) return;
    
    // 1.从字典中取出audioPlayer
    MPMoviePlayerController *audioPlayer = _audioPlayerDict[filename];
    
    // 2.暂停
    if (audioPlayer.playbackState == MPMoviePlaybackStatePlaying) {
        [audioPlayer pause];
    }
}

/**
 *  停止音乐
 *
 *  @param filename 音乐文件名
 */
+ (void)stopMusic:(NSString *)filename
{
    if (!filename) return;
    
    // 1.从字典中取出audioPlayer
    MPMoviePlayerController *audioPlayer = _audioPlayerDict[filename];
    
    // 2.暂停
//    if (audioPlayer.playbackState == MPMoviePlaybackStatePlaying) {
        [audioPlayer stop];
        
        // 直接销毁
        [_audioPlayerDict removeObjectForKey:filename];
//    }
}



@end
